package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        String sql = "select * from tb_goods";
        try{
            conn = dataSource.getConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            List<Map<String,Object>> list = new ArrayList<>();
            while(rs.next()){
                list.add(ys(rs));

            } return list;
        }catch (SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            close(rs,statement,conn);
        }
    }

    private Map<String, Object> ys(ResultSet rs) throws SQLException {
        Map<String,Object> map = new HashMap<>();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1 ; i<= rsmd.getColumnCount() ; i++){
            map.put(rsmd.getColumnName(i),rs.getObject(rsmd.getColumnName(i)));
        }
        return map;
    }



    public void close(ResultSet rs,Statement statement,Connection conn){
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
